import axios from 'axios'
import router from "../router";
import { AxiosRequestAuthorization, AxiosRequestHeader } from "./request-tools";
import { ElMessage } from "element-plus";
import { local } from "../utils/storage";


// +--------------------------------------------------
// | 请求拦截器
// +--------------------------------------------------
axios.interceptors.request.use(config => {
  config = AxiosRequestHeader(config);
  config = AxiosRequestAuthorization(config);
  return config;
}, error => {
  return Promise.reject(error)
})


// +--------------------------------------------------
// | 响应拦截器
// +--------------------------------------------------
axios.interceptors.response.use(res => {

  // 保存刷新后的 TOKEN
  const token = res.headers?.authorization || '';
  if (token) {
    local.set('ADMIN.TOKEN', token)
  }

  if (res.data.code !== 200) {
    return Promise.reject(res.data);
  }

  if (res.data?.data?.hasOwnProperty('list')) {
    return Promise.resolve(res.data.data.list)
  }
  return Promise.resolve(res.data)

}, error => {
  console.info('request.js =>', error)

  if (error.response?.status === 401) {
    ElMessage.error('抱歉，您的登录状态已失效，请重新登录')
    return router.push({ path: '/login' });
  }

  if (error.response?.status === 404) {
    return Promise.reject(`Not Found：[ /api${error.config.url} ]`);
  }

  if ([405, 500].includes(error.response.status)) {
    return Promise.reject(error.response.data.message)
  }

  return Promise.reject(error.response.statusText);
})


// +--------------------------------------------------
// | 请求方式：GET | POST | PUT | DELETE
// +--------------------------------------------------

const request = {
  get(url, params) {
    return new Promise((resolve) => {
      axios.get(url, { params })
           .then(e => resolve(e))
           .catch(err => ElMessage.error(err.msg || err))
    });
  },
  post(url, data, params) {
    return new Promise((resolve) => {
      axios.post(url, data, { params })
           .then(e => resolve(e))
           .catch(err => ElMessage.error(err.msg || err))
    });
  },
  put(url, data, params) {
    return new Promise((resolve) => {
      axios.put(url, data, { params })
           .then(e => resolve(e))
           .catch(err => ElMessage.error(err.msg || err))
    });
  },
  delete(url, data) {
    return new Promise((resolve) => {
      axios.delete(url, data)
           .then(e => resolve(e))
           .catch(err => ElMessage.error(err.msg || err))
    });
  },
  http(method, url, data) {
    const config = { method, url };

    (method.toString().toLowerCase() === 'get') ? config['params'] = data : config['data'] = data;

    return new Promise((resolve, reject) => {
      axios.request(config)
           .then(e => resolve(e))
           .catch(err => reject(err))
    });
  },
}

export default request
